import { getImageCaptcha, getSmsCodeByImgCaptcha, bpaiLogin } from '../../api/index'
import { regular } from '../../utils/verification'
import { showLoading, showToast, hideLoading } from '../../utils/toast'
import { setTokenValue, getTokenValue, removeTokenValue, setLoginMsg, setUserInfo, getLoginMsg } from '../../utils/storage'
import { trackingEventMap, trackingEvent } from '../../utils/tracking'
import { adRequest } from '../../utils/request'
const computedBehavior = require("miniprogram-computed").behavior;

Page({
  data: {
    redirectUrl: '',
    phone: '',
    imgCode: '', // 图形验证码
    smsCode: '', // 短信验证码
    agreeCheck: false,
    timer: null,
    submitLoading: false,
    popupShow: false,
    popupPrivacyShow: false,
    downTime: '获取短信验证码',
    codeObj: {
      image: '',
      imageKey: '',
    },
  },
  behaviors: [computedBehavior],
  onLoad(options) {
    if (options.logout && options.logout == 1) {
      removeTokenValue()
    }
    if (options.redirectUrl) {
      this.setData({
        redirectUrl: options.redirectUrl
      })
    }
    this.getImageCaptcha()
    if (getLoginMsg()) {
      this.setData({
        phone: getLoginMsg(),
        agreeCheck: true
      })
    }
  },
  onShow() {
    if (getTokenValue()) {
      wx.redirectTo({
        url: '/pages/chatView/chatView'
      })
    }
  },
  computed: {
    canSubmit(data) {
      return !(data.phone && data.imgCode && data.smsCode)
    },
  },
  onClose() {
    this.setData({ popupShow: false });
  },
  onPrivacyClose() {
    this.setData({ popupPrivacyShow: false });
  },
  // 获取图形验证码
  async getImageCaptcha() {
    let result = await getImageCaptcha()
    this.setData({
      ['codeObj.image']: result.image,
      ['codeObj.imageKey']: result.key,
    })
  },
  // 倒计时
  countDown() {
    if (!this.data.timer) {
      this.data.timer = setInterval(() => {
        if (this.data.downTime > 1) {
          this.setData({
            downTime: this.data.downTime - 1,
          })
        } else {
          clearInterval(this.data.timer)
          this.setData({
            timer: null,
            downTime: '获取短信验证码',
          })
        }
      }, 1000)
    }
  },
  // 获取短信验证码
  async getCode() {
    let { phone, imgCode, codeObj, downTime } = this.data
    if (downTime !== '获取短信验证码' && downTime >= 0) {
      return
    }
    if (!phone || !regular.phone.test(phone)) {
      showToast('手机号码不正确')
      return
    }
    if (!imgCode) {
      showToast('图形验证码不能为空')
      return
    }
    this.setData({
      downTime: 60,
    })
    this.countDown()
    try {
      showLoading('验证码发送中')
      let result = await getSmsCodeByImgCaptcha({
        busType: '101000',
        phone,
        captchaKey: codeObj.imageKey,
        captchaCode: imgCode,
      })
      hideLoading()
      showToast('发送成功', 'success', 1500)
      trackingEvent(trackingEventMap.loginSmsGet)
    } catch (error) {
      if (this.data.timer) {
        clearInterval(this.data.timer)
      }
      this.setData({
        timer: null,
        downTime: '获取短信验证码',
      })
      hideLoading()
      this.getImageCaptcha()
    }
  },
  // 勾选
  checkChange(event) {
    this.setData({
      agreeCheck: event.detail,
    });
  },
  // 用户协议
  goPage() {
    this.setData({ popupShow: true });
  },
  // 用户协议
  goPrivacyPage() {
    this.setData({ popupPrivacyShow: true });
  },
  // 登录
  async login() {
    let { phone, imgCode, smsCode, agreeCheck } = this.data
    if (!phone || !regular.phone.test(phone)) {
      showToast('手机号码不正确')
      return
    }
    if (!imgCode) {
      showToast('图形验证码不能为空')
      return
    }
    if (!smsCode) {
      showToast('短信验证码不能为空')
      return
    }
    if (!agreeCheck) {
      showToast('请勾选用户协议')
      return
    }
    try {
      this.setData({
        submitLoading: true
      })
      const globalData = getApp().globalData
      let result = await bpaiLogin({
        channelCode: globalData.extraMsg.channelCode || '',
        inviterCode: globalData.extraMsg.inviterCode || '',
        sourceTag: globalData.extraMsg.sourceTag || '',
        phone,
        smsCode,
        regChannel: 'BPai_applet'
      })
      console.info('login')
      console.info({
        channelCode: globalData.extraMsg.channelCode || '',
        inviterCode: globalData.extraMsg.inviterCode || '',
        sourceTag: globalData.extraMsg.sourceTag || '',
        phone,
        smsCode,
        regChannel: 'BPai_applet'
      })
      setTokenValue(result.token)
      setLoginMsg(phone)
      this.setData({
        submitLoading: false
      })

      let sourceTag = 1
      if (globalData.activityConfig.activitySwitch == '1') {
        sourceTag = 2
      }
      let redirectUrl = this.data.redirectUrl
      wx.redirectTo({
        url: `/pages/chatView/chatView?sourceTag=${sourceTag}&redirectUrl=${redirectUrl}`
      })
      if (result.newUserTag && globalData.gdtVid) {
        await adRequest({
          gdtVid: globalData.gdtVid,
          actionType: "REGISTER"
        })
      }
      trackingEvent(trackingEventMap.phoneCodeLogin)
    } catch (error) {
      this.setData({
        submitLoading: false
      })
    }

  }
})
